<template>
  <div class="medicine-list">
    <el-card>
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="药品名称">
          <el-input v-model="searchForm.name" placeholder="请输入药品名称" />
        </el-form-item>
        <el-form-item label="药品分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="正常" value="normal" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">新增药品</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="medicineStore.loading"
        :data="medicineStore.list"
      >
        <el-table-column prop="code" label="药品编码" width="120" />
        <el-table-column prop="name" label="药品名称" width="150" />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="manufacturer" label="生产厂家" width="200" />
        <el-table-column prop="price" label="单价" width="100">
          <template #default="{ row }">
            ¥{{ row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100">
          <template #default="{ row }">
            <el-tag :type="row.stock <= row.minStock ? 'danger' : 'success'">
              {{ row.stock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'normal' ? 'success' : 'danger'">
              {{ row.status === 'normal' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              link 
              :type="row.status === 'normal' ? 'danger' : 'success'"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'normal' ? '禁用' : '启用' }}
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="medicineStore.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增药品' : '编辑药品'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="药品名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="药品编码" prop="code">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="药品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="form.specification" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="form.manufacturer" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input-number 
            v-model="form.price" 
            :precision="2" 
            :step="0.1" 
            :min="0"
          />
        </el-form-item>
        <el-form-item label="最低库存" prop="minStock">
          <el-input-number 
            v-model="form.minStock" 
            :precision="0" 
            :step="1" 
            :min="0"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useMedicineStore } from '@/store/medicine'
import type { MedicineForm } from '@/types/medicine'

const medicineStore = useMedicineStore()

// 搜索表单
const searchForm = reactive({
  name: '',
  categoryId: '',
  status: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 分类数据（模拟）
const categories = ref([
  { id: 1, name: '处方药' },
  { id: 2, name: '非处方药' },
  { id: 3, name: '中药' },
  { id: 4, name: '西药' }
])

// 对话框
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const form = reactive<MedicineForm>({
  code: '',
  name: '',
  categoryId: 0,
  specification: '',
  unit: '',
  manufacturer: '',
  price: 0,
  minStock: 0,
  status: 'normal',
  remark: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入药品编码', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择药品分类', trigger: 'change' }],
  specification: [{ required: true, message: '请输入规格', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  manufacturer: [{ required: true, message: '请输入生产厂家', trigger: 'blur' }],
  price: [{ required: true, message: '请输入单价', trigger: 'blur' }],
  minStock: [{ required: true, message: '请输入最低库存', trigger: 'blur' }]
})

// 初始化
onMounted(() => {
  handleSearch()
})

// 搜索
const handleSearch = () => {
  medicineStore.fetchList({
    ...searchForm,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  })
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.categoryId = ''
  searchForm.status = ''
  currentPage.value = 1
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  // 重置表单
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  form.status = 'normal'
  form.price = 0
  form.minStock = 0
}

// 编辑
const handleEdit = async (row: any) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  const detail = await medicineStore.fetchDetail(row.id)
  // 填充表单
  Object.keys(form).forEach(key => {
    form[key] = detail[key]
  })
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除药品 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    await medicineStore.delete(row.id)
    ElMessage.success('删除成功')
    handleSearch()
  })
}

// 切换状态
const handleToggleStatus = (row: any) => {
  const action = row.status === 'normal' ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确定要${action}药品 ${row.name} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    await medicineStore.updateStatus(row.id, row.status === 'normal' ? 'disabled' : 'normal')
    ElMessage.success(`${action}成功`)
    handleSearch()
  })
}

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        await medicineStore.add(form)
      } else {
        await medicineStore.update(medicineStore.currentMedicine!.id, form)
      }
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
      dialogVisible.value = false
      handleSearch()
    }
  })
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  handleSearch()
}

// 页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  handleSearch()
}
</script>

<style scoped>
.medicine-list {
  padding: 20px;
}
.search-form {
  margin-bottom: 20px;
}
.toolbar {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 